﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using UIWindows.Tools.Helper;
using XCode;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    /// 装盘机左扫码
    /// </summary>
    public class TrayFillerLeftScanBarcode : HelperBase
    {
        PLCBase InjMachine { get; set; }

        MESWinderOutRecordAddRec _mesWinderOutRecord { get; set; }
        public TrayFillerLeftScanBarcode(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine =  deviceModel.PLC;
            _mesWinderOutRecord = new MESWinderOutRecordAddRec(_log, _dialog);
        }
        public override Task Handle()
        {
            if (_parameter == null) return base.Handle();

            //await Task.Yield();
            short testResult = 2;
            RunLog($"-{ machineInfo_Type.ToString()}{_deviceModel.Index}左扫码开始");
            
            try
            {
                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
               && x.TaskType == TaskTypes.装盘左扫码&&x.Index==_deviceModel.Index);
                if (device == null)
                {
                    RunLog($"-{ machineInfo_Type.ToString()}{_deviceModel.Index}左扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return base.Handle();
                }
                var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);
                if (string.IsNullOrWhiteSpace(barcode)||barcode.Contains("ERROR"))
                {
                    testResult = 2;
                    RunLog($"{ machineInfo_Type.ToString()}{_deviceModel.Index}【左扫码】扫码失败");
                }
                else
                {
                    testResult = 1;
                    try
                    {
                        var entityType = GetEntityType();
                        var entity = CreateEntityType<object>();

                        // 设置数据库表名
                        PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                        tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);
                        var dateNow = DateTime.Now;

                        var entityData = entity as TrayFillerLeftData;
                        entityData.LoadInboundTime = dateNow;
                        entityData.AcquisitionTime = dateNow;
                        entityData.NumPerPallet = "132";
                        entityData.PalletNo = barcode;
                        entityData.Position = (int)ScanPositionType.左扫码;
                        entityData.Insert();
                        _homeStatic.AddBattery(entityData, machineInfo_Type);


                    }
                    catch (Exception ex)
                    {
                        RunLog($"{ machineInfo_Type.ToString()}{_deviceModel.Index}插入数据库【左扫码】发生异常:{ex}");
                    }

                    if (_parameterStatic.DecideParameter.EnableMES)
                    {
                        //上传MES
                        MESWinderOutRecordAddRecUpload(_mesWinderOutRecord, barcode);
                    }

                    
                    RunLog($"{ machineInfo_Type.ToString()}{_deviceModel.Index}【左扫码】扫码成功：{barcode}");
                }
            }
            catch (Exception ex)
            {
                RunLog($"{ machineInfo_Type.ToString()}{_deviceModel.Index}【左扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write("DM1101", new short[] { testResult });
                var r2 = InjMachine.Write("DM1100", new short[] { 1 });
                var r3 = InjMachine.Write("DM1000", new short[] { 0 });
                RunLog($"{ machineInfo_Type.ToString()}{_deviceModel.Index}【左扫码】写结果信号 {testResult} {r1}.{r2}.{r3} {(r1 && r2 && r3 ? "成功" : "失败")}");
            }

            return base.Handle();

            //return Task.CompletedTask;
        }
    }
}
